package com.syh.app.basic.service;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.syh.app.basic.App;
import com.syh.app.basic.service.utils.WsDataManager;
import com.syh.app.basic.utils.Loog;
import com.syh.app.basic.service.base.MessageType;
import com.syh.app.basic.service.base.NetworkChangedReceiver;
import com.syh.app.basic.service.base.WsCMD;
import com.syh.app.basic.service.base.WsHost;
import com.syh.app.basic.service.base.WsThread;
import com.syh.app.basic.service.impl.Response;
import com.syh.app.basic.service.impl.WsStatueListener;
import com.syh.app.basic.service.pojo.ErrorResponse;
import com.syh.app.basic.service.pojo.WebSocketRequest;
import com.syh.app.basic.service.utils.DataUtils;
import com.syh.app.basic.service.utils.HeartBeatUtils;
import com.syh.app.basic.service.utils.WsConstant;
import com.syh.app.basic.service.utils.WsUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;

/**
 * 描    述：WebSocketService
 */
public class WsService extends Service implements WsStatueListener {
    private static final String TAG = "WsService";
    private Gson mGson = new Gson();

    private WsThread klineThread, sendThread;
    private NetworkChangedReceiver networkChangedReceiver;

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);

        //K线模块
        if (klineThread == null) {
            klineThread = new WsThread(WsConstant.CODE_KLINE, WsHost.klineWssUrl);
            klineThread.setSocketListener(this);
            klineThread.start();
        }

        //绑定监听网络变化广播
        networkChangedReceiver = new NetworkChangedReceiver(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        filter.addAction("android.net.wifi.STATE_CHANGE");
        registerReceiver(networkChangedReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Loog.e(TAG, "------onDestroy----");
        //停止心跳
        HeartBeatUtils.getInstance().stopAllHeartBeat();
        unregisterReceiver(networkChangedReceiver);
        EventBus.getDefault().unregister(this);
        if (klineThread != null) {
            klineThread.getHandler().sendEmptyMessage(MessageType.QUIT);
        }
        if (sendThread != null) {
            sendThread.getHandler().sendEmptyMessage(MessageType.QUIT);
        }
        App.getApplication().setServiceAlive(false);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEvent(WebSocketRequest webSocketRequest) {
        if (null != webSocketRequest.getBody()) {
            Loog.d(TAG, webSocketRequest.getCode() + "---" + webSocketRequest.getCmd() + "---" + new String(webSocketRequest.getBody()));
        }
        senBytes(webSocketRequest.getCode(), DataUtils.initBytes(webSocketRequest.getCmd(), webSocketRequest.getBody()));
    }

    /**
     * 发送数据
     *
     * @param type
     * @param bytes
     */
    public void senBytes(int type, byte[] bytes) {
        switch (type) {
            case WsConstant.CODE_KLINE:
                sendThread = klineThread;
                break;
        }
        if (sendThread.getHandler() == null) {
            ErrorResponse errorResponse = new ErrorResponse();
            errorResponse.setErrorCode(3);
            errorResponse.setCause(new Throwable("WebSocket does not initialization!"));
            errorResponse.setRequestText(Arrays.toString(bytes));
            onSendMessageError(type, errorResponse);
        } else {
            Message message = sendThread.getHandler().obtainMessage();
            message.obj = bytes;
            message.what = MessageType.SEND_MESSAGE;
            sendThread.getHandler().sendMessage(message);
        }
    }

    /**
     * 重连
     */
    public void reconnect() {
        Loog.d(TAG, "reconnect");
        if (klineThread.getHandler() == null) {
            onConnectError(WsConstant.CODE_KLINE, new Throwable("WebSocket is not ready"));
        } else {
            klineThread.getHandler().sendEmptyMessage(MessageType.CONNECT);
        }
    }

    @Override
    public void onConnected(int type) {
        switch (type) {
            //K线
            case WsConstant.CODE_KLINE:
                Loog.e(TAG, "K线WebSocket连接成功！");
                HeartBeatUtils.getInstance().startKlineHeartBeat();
                //BB 行情
                senBytes(WsConstant.CODE_KLINE, DataUtils.initBytes(WsCMD.SUBSCRIBE_THUMB, mGson.toJson(WsUtils.setSubscribeThumbSPOTJsonMap()).getBytes()));
                break;
        }
    }

    @Override
    public void onConnectError(int type, Throwable cause) {
        Loog.e(TAG, type + "-->onConnectError");
    }

    @Override
    public void onDisconnected(int type) {
        Loog.e(TAG, type + "-->onDisconnected");
    }

    @Override
    public void onMessageResponse(int type, Response message) {
        synchronized (this) {
            WsDataManager.getInstance().dealWsResponse(type, message);
        }
    }

    @Override
    public void onSendMessageError(int type, ErrorResponse error) {
        Loog.e(TAG, "onSendMessageError" + error.toString());
    }
}
